import {create} from "zustand";
import {persist} from "zustand/middleware";
import {login} from "@/apis/auth";

export type AccessControlStore = {
    accessCode: string;
    token: string;
    accessCodeErrorMsgs: string;

    updateToken: (_: string) => void;
    updateCode: (_: string) => void;

    isAuthorized: () => boolean;
    login: () => Promise<any>;
    goToLogin: () => void;
}

export const useAccessStore = create<AccessControlStore>()(
    persist((set, get) => ({
            token: "",
            accessCode: "4567",
            accessCodeErrorMsgs: "",
            updateCode(code: string) {
                set(() => ({accessCode: code}));
            },
            updateToken(token: string) {
                set(() => ({token: token}));
            },
            goToLogin() {
                get().updateCode("");
                get().updateToken("");
            },
            isAuthorized() {
                return !!get().token;
            },
            async login() {
                const res = await login(get().accessCode);
                get().updateToken(res.data);
                set(() => ({accessCodeErrorMsgs: ""}));
                return res;
            },
        }),
        {
            name: "chat-access",
            version: 1,
        }
    )
);